package com.lmoumou.lib_pdfload.view

import android.annotation.SuppressLint
import android.content.Context
import android.os.Build
import android.os.Handler
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.webkit.WebChromeClient
import android.webkit.WebView
import android.webkit.WebViewClient
import android.widget.FrameLayout
import com.lmoumou.lib_pdfload.R
import com.lmoumou.lib_pdfload.code.BASE64Encoder
import java.io.UnsupportedEncodingException

/**
 * @author Lmoumou
 * @date : 2019/8/27 16:03
 */
class DWebView(context: Context, attrs: AttributeSet, defStyleAttr: Int) : FrameLayout(context, attrs, defStyleAttr) {
    private val webView: WebView
    private val progressBar: NumberProgressBar
    private var isSetting = true
    internal var isProgress = true
    var listener: ProgressListener? = null

    init {
        LayoutInflater.from(getContext()).inflate(R.layout.widget_webview, this)
        webView = findViewById(R.id.webView)
        progressBar = findViewById(R.id.progressBar)
        val mTypedArray = context.obtainStyledAttributes(attrs, R.styleable.DWebView)
        isSetting = mTypedArray.getBoolean(R.styleable.DWebView_dwv_isSetting, true)
        isProgress = mTypedArray.getBoolean(R.styleable.DWebView_dwv_isProgress, true)
        if (isSetting) {
            webViewSetting()
        }
        webView.webViewClient = object : WebViewClient() {
            override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
                view.loadUrl(url)
                return true
            }
        }
        webView.webChromeClient = object : WebChromeClient() {
            override fun onProgressChanged(view: WebView, newProgress: Int) {
                super.onProgressChanged(view, newProgress)

                listener?.LoadProgress(newProgress)

                if (isProgress) {
                    progressBar.progress = newProgress
                    if (newProgress > 0 && progressBar.visibility == View.GONE) {
                        progressBar.visibility = View.VISIBLE
                    }

                    if (newProgress == 100 && progressBar.visibility == View.VISIBLE) {
                        Handler().postDelayed({ progressBar.visibility = View.GONE }, 2000)
                    }
                }
            }
        }
        mTypedArray.recycle()
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun webViewSetting() {
        val settings = webView.settings
        settings.savePassword = false
        settings.javaScriptEnabled = true
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            settings.allowFileAccessFromFileURLs = true
            settings.allowUniversalAccessFromFileURLs = true
        }
        settings.setSupportZoom(true)
        settings.builtInZoomControls = true
    }

    fun LoadPDF(docPath: String) {
        var docPath = docPath
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//api >= 19
            webView.loadUrl("file:///android_asset/pdf/pdf.html?$docPath")
        } else {
            if (!TextUtils.isEmpty(docPath)) {
                var bytes: ByteArray? = null
                try {// 获取以字符编码为utf-8的字符
                    bytes = docPath.toByteArray(charset("UTF-8"))
                } catch (e: UnsupportedEncodingException) {
                    e.printStackTrace()
                }

                if (bytes != null) {
                    docPath = BASE64Encoder().encode(bytes)// BASE64转码
                }
            }
            webView.loadUrl("file:///android_asset/pdf/pdf.html?$docPath")
        }
    }
}